<template>
  <div class="body-info">
    <!-- 顶部信息 -->
    <div class="top-all-info">
      <el-form ref="Semester" type="flex" :model="Semester">
        <el-row id="selectTerm">
          <el-col :span="14">
            <el-form-item
              min-width="100%"
              prop="semId"
            >
              <el-select
                v-model="Semester.semId"
                filterable
                :placeholder="semName"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in semesterData"
                  :key="item.semId"
                  :label="item.semName"
                  :value="item.semId"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-button

            type="primary"
            style="margin-left:10px"
            @click="handleSerch(Semester)"
          >查询</el-button>

        </el-row>
      </el-form>
      <!-- 顶部标题 -->
      <div class="top-title">分数统计</div>
      <!-- 顶部内容 -->
      <div class="top-info-info">
        <el-row>
          <el-col :span="8">
            <!-- 用户统计 -->
            <div class="top-left-card">
              <el-row>
                <el-col :span="18">
                  <!-- 左侧信息展示 -->
                  <div class="top-card-left-top">当前用户人数</div>
                  <div class="top-card-left-second">{{ allScoreRanking.length }}</div>
                </el-col>
                <el-col :span="6">
                  <!-- 右侧图标展示 -->
                  <img src="../../icons/png/user.png" class="top-card-right-img">
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col :span="8">
            <!-- 平均分 -->
            <div class="top-center-card">
              <el-row>
                <el-col :span="18">
                  <!-- 左侧信息展示 -->
                  <div class="top-card-left-top">党支部平均分</div>
                  <div class="top-card-left-second">{{ allAvScore }}</div>
                </el-col>
                <el-col :span="6">
                  <!-- 右侧图标展示 -->
                  <img src="../../icons/png/average.png" class="top-card-right-img">
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col :span="8">
            <!-- 总及格率 -->
            <div class="top-right-card">
              <el-row>
                <el-col :span="18">
                  <!-- 左侧信息展示 -->
                  <div class="top-card-left-top">党支部及格率</div>
                  <div class="top-card-left-second">{{ allPR }}%</div>
                </el-col>
                <el-col :span="6">
                  <!-- 右侧图标展示 -->
                  <img src="../../icons/png/pass.png" class="top-card-right-img">
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 中部全部信息 -->
    <el-row>
      <el-col :span="12">
        <!-- 成绩分析 -->
        <div class="left-all-info">
          <el-row>
            <el-col :span="15">
              <!-- 顶部标题 -->
              <div class="top-title">成绩分析</div>
            </el-col>
            <el-col :span="9">
              <!-- 右侧选择器 -->
              <div class="left-right-select">
                <el-select v-model="pieSelectValue" :placeholder="pieSelectValue" @change="pieSelect">
                  <el-option
                    v-for="item in pieOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </el-col>
          </el-row>

          <!-- 饼图 -->
          <div class="pie-all-info">
            <div id="pieScore" class="pie-info" />
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <!-- 成绩排名 -->
        <div class="right-all-info">
          <!-- 顶部标题 -->
          <div class="top-title">党小组统计</div>
          <!-- 党小组排名 -->
          <el-table
            :data="branchRanking"
            border
            fit
            class="right-all-info-table"
          >
            <el-table-column
              prop="branchName"
              label="党小组"
              min-width="12%"
              align="center"
            />
            <el-table-column
              prop="branchAv"
              label="平均分"
              min-width="12%"
              align="center"
              sortable
            />
            <el-table-column
              prop="branchPr"
              label="及格率"
              min-width="12%"
              align="center"
              sortable
            />
            <el-table-column
              prop="topUserName"
              label="小组最高分姓名"
              min-width="12%"
              align="center"
            />
            <el-table-column
              prop="topUserScore"
              label="小组最高分"
              min-width="12%"
              align="center"
              sortable
            />
          </el-table>
        </div>

      </el-col>
    </el-row>

  </div>
</template>
<script>
import { getAllRanking, selectAllAvScore, getAllRankingByBranch, getshowData } from '../../api/ranking.js'
import { getAllTotal, totalCount } from '../../api/total.js'
import { getAllSemester, findNowSemesterByID, getSemester } from '../../api/semester.js'
import { getAllInfo, getAllUserInfo } from '../../api/user.js'
import { forUserGetSend } from '../../api/send.js'
import { getGroups } from '../../api/branch.js'
export default {
  data() {
    return {
      jugesemId: '',
      semesterData: {},
      Semester: {},
      storesmId: '',
      // 存入的semId
      semId: '',
      semName: '',
      totalScoreAverage: '',
      // 所有人排名
      allScoreRanking: [],
      // 所有人平均分
      allAvScore: '',
      // 所有人及格率
      allPR: '',
      // 当前学期各党小组成绩分布
      allBranchPie: [],
      // 党小组排名
      branchRanking: [],
      // 饼图
      scorePie: {},
      scorePieOpinion: ['90分以上', '80-90分', '70-80分', '60-70分', '60分以下'],
      scorePieOpinionData: [],
      allBranch: [],
      // 饼图选择器
      pieOptions: [
        {
          value: '0',
          label: '全部成员'
        }],
      pieSelectValue: '',
      userScoreStatus: '',
      lookStatus: true
    }
  },
  created() {
    // 获取展示当前状态
    this.getCreateSemId()
    this.getinfo()
    this.getshowdata()
    this.handleshow()
    // 获取党小组信息
    this.getAllBranch()
  },
  mounted() {
    this.roundCake('pieScore')
  },
  methods: {
    // 回显select选择框
    handleshow() {
      findNowSemesterByID(this.semId).then((resp) => {
        this.semesterData.semId = resp.obj.semId
        this.semesterData.semName = String(resp.obj.semName)
      })
    },
    // 点击查询的方法
    handleSerch(Semester) {
      this.lookStatus = true
      this.getShowStatus(Semester.semId)
      this.getinfo()
      this.getshowdata()
    },
    getinfo: function() {
      getAllSemester().then((resp) => {
        this.semesterData = resp.obj
      })
    },
    // 访问页面后，调取学期状态
    getCreateSemId() {
      var a = sessionStorage.getItem('semId')
      // 根据semId存储sem信息
      if (a === '无开放学期') {
        getSemester('1').then((res) => {
          this.semName = res.obj.semName
        })
      } else {
        getSemester(a).then((res) => {
          this.semName = res.obj.semName
        })
      }

      this.getShowStatus(a)
    },
    // 获取展示当前状态
    getShowStatus(a) {
      var that = this
      new Promise(function(resolve, reject) {
        if (a === '无开放学期') {
          that.semId = '1'
          resolve()
        } else {
          that.semId = a
          resolve()
        }
      }).then(() => {
        // 判断当前学期的成绩状态
        that.getAllUserInfo(that.semId)
      })
    },
    // 根据登录权限获取所有用户信息
    getAllUserInfo(semId) {
      getAllUserInfo().then((res) => {
        // 获取当前权限
        const userType = sessionStorage.getItem('user_Type')
        let userInfo = []
        // 如果是党小组权限 只能查看党小组信息
        if (userType === '6') {
          getAllInfo(sessionStorage.getItem('userId')).then((data) => {
            const userBranch = data.obj.userinfo.userBranch
            for (const i in res.obj) {
              if (res.obj[i].userinfo.userBranch === userBranch) {
                userInfo.push(res.obj[i].userinfo)
              }
            }
          })
        } else {
          userInfo = res.obj.map((item) => (item.userinfo))
        }
        // 根据用户名称，查找用户信息
        this.isSemScoreStatus(userInfo, semId)
      })
    },
    // 判断当前学期的成绩状态
    isSemScoreStatus(userInfo, semId) {
      var that = this
      new Promise((resolve) => {
        getAllTotal().then((data) => {
          userInfo.map(async(item, index) => {
            const totalInfo = data.obj.find(total => total.totalSemId === +semId && total.totalUserId === item.userId)
            if (totalInfo) item.totalScore = totalInfo.totalScore
            const { obj: send } = await forUserGetSend(semId, item.userId)
            const sendScoreMap = send ? send.map((item) => item.sendScore ? item.sendScore : 0) : []
            const sendScore = sendScoreMap.length > 0 ? sendScoreMap.reduce((pre, cur) => pre + cur) : 0
            userInfo[index] = {
              ...item,
              send,
              totalInfo: {
                sendScore,
                totalScore: item.totalScore ? item.totalScore : 0,
                sendStatus: sendScore === item.totalScore ? '已发布' : '未发布'
              }
            }
            if (sendScore !== item.totalScore) {
              this.lookStatus = false
            }
            if (index === userInfo.length - 1) {
              resolve()
            }
          })
        })
      }).then(() => {
        if (this.lookStatus === false) {
          this.$confirm('当前成绩未发布，无法生成成绩统计。点击确定后可到达成绩管理页面', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.$router.push({ path: that.redirect || '/scoreManage/scoreManage' })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消跳转'
            })
          })
        } else {
          this.getAllRankingInfo(semId)
          this.getAllAvScoreInfo(semId)
          this.getAllPrInfo(semId)
          this.getBranchRanking(semId)
        }
        setTimeout(() => {
          that.userInfo = userInfo
          that.loading = false
        }, 500)
      })
    },
    getAllRankingInfo(semId) {
      var that = this
      new Promise(function(resolve, reject) {
        getAllRanking(semId).then(res => {
          resolve(res.obj)
        })
      }).then((data) => {
        this.pieSelectValue = '全部成员'
        that.allScoreRanking = data
      })
    },
    // 获取党支部平均分
    getAllAvScoreInfo(semId) {
      var that = this

      new Promise(function(resolve, reject) {
        selectAllAvScore(semId).then(res => {
          resolve(res.obj)
        })
      }).then((data) => {
        that.allAvScore = data.avgScore.toFixed(2)
      })
    },
    // 获取党支部及格率
    getAllPrInfo(semId) {
      var that = this
      new Promise(function(resolve, reject) {
        selectAllAvScore(semId).then(res => {
          resolve(res.obj)
        })
      }).then((data) => {
        that.allPR = data.PassRate.toFixed(2)
      })
    },
    // 当前饼图选择状态
    pieSelect(value, a) {
      // 判断是否查询的是全部的信息
      var that = this
      var data = this.allBranchPie
      value = parseInt(value)
      if (that.scorePieOpinionData !== []) {
        that.scorePieOpinionData = []
      }
      if (value === 0) {
        this.getshowdata()
      } else {
        var j = 0
        if (data['90以上'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['90以上'][value - 1]['total_score'],
            name: '90分以上',
            itemStyle: '#2ecc71'
          }
          j++
        }
        if (data['80-90'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['80-90'][value - 1]['total_score'],
            name: '80-90分',
            itemStyle: '#3498db'
          }
          j++
        }
        if (data['70-80'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['70-80'][value - 1]['total_score'],
            name: '70-80分',
            itemStyle: '#9b59b6'
          }
          j++
        }
        if (data['60-70'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['60-70'][value - 1]['total_score'],
            name: '60-70分',
            itemStyle: '#e67e22'
          }
          j++
        }
        if (data['60以下'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['60以下'][value - 1]['total_score'],
            name: '60分以下',
            itemStyle: '#e74c3c'
          }
          j++
        }
        that.roundCake('pieScore')
      }
    },

    // 获取所有党小组排名
    getBranchRanking(semId) {
      var that = this
      getAllRankingByBranch(semId).then(res => {
        const allBranch = []
        let branchRanking = {}
        const userAllBranch = this.pieOptions
        for (let i = 1; i < userAllBranch.length; i++) {
          let addStatus = true
          for (let j = 0; j < res.obj.totalScoreAverage.length; j++) {
            if (parseInt(userAllBranch[i].value) === res.obj.totalScoreAverage[j].user_branch) {
              branchRanking = {
                branchName: '第' + i + '党小组',
                branchAv: res.obj.totalScoreAverage[j].total_score.toFixed(2),
                branchPr: res.obj.totalScorePassRate[j].total_score + '%',
                topUserName: res.obj.totalScoreMaxScore[j].user_name,
                topUserScore: res.obj.totalScoreMaxScore[j].total_score
              }
              allBranch.push(branchRanking)
              addStatus = false
              break
            }
          }
          if (addStatus === true) {
            branchRanking = {
              branchName: '第' + i + '党小组',
              branchAv: 0,
              branchPr: 0 + '%',
              topUserName: '未发现数据',
              topUserScore: '未发现数据'
            }
            allBranch.push(branchRanking)
          }
        }
        that.branchRanking = allBranch
      })
    },
    // 获取所有党小组信息
    getAllBranch() {
      var that = this
      getGroups().then((res) => {
        that.allBranch = res.obj
        for (let i = 0; i < res.obj.length; i++) {
          if (res.obj[i].branchType === 1) {
            const branch = {
              value: res.obj[i].branchId.toString(),
              label: res.obj[i].branchName.toString()
            }
            that.pieOptions.push(branch)
          }
        }
      })
    },
    // 获取饼状图数据
    getshowdata() {
      var that = this
      var semId = this.semId
      new Promise(function(resolve, reject) {
        // 当前总体分数段数据
        getshowData(semId).then(res => {
          // 党小组分数段数据
          totalCount(semId).then((allBranchPie) => {
            that.allBranchPie = allBranchPie.obj
            resolve(res.obj)
          })
        })
      }).then((data) => {
        var j = 0
        that.scorePieOpinionData = []
        if (data['90以上'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['90以上'],
            name: '90分以上',
            itemStyle: '#2ecc71'
          }
          j++
        }
        if (data['80-90'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['80-90'],
            name: '80-90分',
            itemStyle: '#3498db'
          }
          j++
        }
        if (data['70-80'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['70-80'],
            name: '70-80分',
            itemStyle: '#9b59b6'
          }
          j++
        }
        if (data['60-70'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['60-70'],
            name: '60-70分',
            itemStyle: '#e67e22'
          }
          j++
        }
        if (data['60以下'] !== 0) {
          that.scorePieOpinionData[j] = {
            value: data['60以下'],
            name: '60分以下',
            itemStyle: '#e74c3c'
          }
          j++
        }
        that.roundCake('pieScore')
      })
    },

    // 圆饼图生成
    roundCake(id) {
      var echarts = require('echarts')
      // 基于准备好的dom，初始化echarts实例
      this.scorePie = echarts.init(document.getElementById(id))
      this.scorePie.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}:{c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 5,
          top: 20,
          bottom: 20,
          data: this.scorePieOpinion
        },
        series: [
          {
            name: '状态',
            type: 'pie',
            radius: '60%',
            center: ['40%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              color: function(params) {
                // 自定义颜色
                var colorList = ['#2ecc71', '#3498db', '#9b59b6', '#e67e22', '#e74c3c']
                return colorList[params.dataIndex]
              }
            },
            data: this.scorePieOpinionData
          }
        ]
      })
    }
  }
}
</script>
<style lang="scss">
.body-info{
  background-color: #ecf0f1;
  padding-top: 3rem;
  padding-bottom: 3rem;
}
.top-all-info{
  width: 95%;
  margin-left: 3rem;
  padding-bottom: 3rem;
  padding-top: 1.5rem;
  background-color: #fff;
  border-radius: 0.5rem;
}
.top-info-info{
  margin-top: 1.5rem;
}
.top-title{
  padding-left: 1.5rem;
  padding-bottom: 1rem;
  padding-top: 1rem;
  border-left-style: solid;
  border-left-width: 0.4rem;
  border-left-color: #fd4647;
  font-weight: 600;
  font-size: 1.2rem;
}
.top-left-card{
  width: 20rem;
  background-color: #2a8bf4;
  margin-left: 7rem;
  padding-bottom: 1rem;
  border-radius: 1rem;
  box-shadow:0px 12px 8px -12px #000;
  border-radius:10px;
}
.top-center-card{
  width: 20rem;
  background-color: #e55039;
  margin-left: 7rem;
  padding-bottom: 1rem;
  border-radius: 1rem;
  box-shadow:0px 12px 8px -12px #000;
  border-radius:10px;
}
.top-right-card{
  width: 20rem;
  background-color: #D6A2E8;
  margin-left: 7rem;
  padding-bottom: 1rem;
  border-radius: 1rem;
  box-shadow:0px 12px 8px -12px #000;
  border-radius:10px;
}
.top-card-left-top{
  color: #fff;
  font-size: 1.5rem;
  font-weight: 600;
  padding-top: 1rem;
  padding-left: 2rem;
}
.top-card-left-second{
  color: #fff;
  font-size: 1.2rem;
  padding-top: 0.5rem;
  padding-left: 2rem;
}
.top-card-right-img{
  margin-top: 1.3rem;
  width: 2.5rem;
  height: 2.5rem;
}
.left-all-info{
  width: 94%;
  margin-top: 3rem;
  margin-left: 3rem;
  padding-top: 1.5rem;
  background-color: #fff;
  border-radius: 0.5rem;

}
.right-all-info{
  width: 94%;
  margin-top: 3rem;
  margin-left: 0.6rem;
  margin-right: 3rem;
  padding-bottom: 3rem;
  padding-top: 1.5rem;
  background-color: #fff;
  border-radius: 0.5rem;
}
.pie-all-info{
  width: 100%;
  height: 100%;
  display: flex;//flex布局
  justify-content: center;//使子项目水平居中
  align-items: center;//使子项目垂直居中
}
.pie-info{
  width: 40rem;
  height: 26rem;
}
.left-right-select{
  margin-top: 1rem;
}
.right-all-info-table{
  width: 95%;
  margin-top: 2.5rem;
  margin-left: 1rem;
  margin-bottom: 1.9rem;
}
#selectTerm{
  float: right;
  margin-right: 2%;
}
</style>

